//
//  ARTPelvicFloorTrainingSController.m
//  ChartsDemo
//
//  Created by Kary on 2022/11/22.
//

#import "ARTPelvicFloorTrainingSController.h"
#import "ARTPelvicFloorTrainingModel.h"
#import "ARTTreatmentCommonCell.h"
#import "ARTTreatmentCommonModel.h"
#import "ARTPelvicFloorTrainingCycleCell.h"
#import "ARTPelvicFloorTrainingDetailController.h"
#import "ARTPelvicFloorMusclesHistoryDetailController.h"
#import "ARTTreatmentCommonScrollCell.h"
#import "ARTTreatmentCommonScrollTitleCell.h"
#import "ARTPelvicFloorMusclesDataAnalysis.h"
@interface ARTPelvicFloorTrainingSController ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,ARTTreatmentCommonCellDelegate>
/// 顶部视图collectionView
@property (nonatomic, strong) UICollectionView *topCollectionView;
/// 底部视图
@property (nonatomic, strong) UICollectionView *bottomCollectionView;
@property (nonatomic, strong) UIButton *floatingBtn;
/// 当前页面对应的治疗名称
@property (nonatomic, copy) NSString *contentStr;
/// 治疗方案
@property (nonatomic, copy) NSString *treatmentContent;
@property(nonatomic, assign) NSInteger treatmentIndex;
/// 数据源
@property (nonatomic, strong) NSMutableArray <ARTTreatmentCommonModel *>*dataArrM;
/// 蓝牙相关
@property (strong, nonatomic)  BabyBluetooth *baby;
@property (strong, nonatomic,nullable)  CBPeripheral *currentPeripheral;
@property (strong, nonatomic,nullable)  CBCharacteristic *notifyCharacteristic;
@property (strong, nonatomic,nullable)  CBCharacteristic *writeCharacteristic;
@property (strong, nonatomic) ARTPelvicFloorMusclesDataAnalysis *dataAnalysis;

// 当前训练类型
@property (assign, nonatomic)  ARTPelvicfloormuscleTrainingType  trainingType;

@end

@implementation ARTPelvicFloorTrainingSController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initDataSource];
    [self babyDelegate];
    [self configUI];
}

- (void)initDataSource{
    self.dataArrM = [ARTTreatmentCommonModel creatPelvicFloorTrainingDataSource];
    self.treatmentIndex = 0;
    self.contentStr = @"压力性尿失禁";
    self.treatmentContent = @"常规训练模式（A方案）";
    [self.topCollectionView reloadData];
    [self.bottomCollectionView reloadData];
}


// 设置蓝牙代理
- (void)babyDelegate{
    _baby = ARTSingleShare.baby;
    _currentPeripheral = ARTSingleShare.currentPeripheral;
    _notifyCharacteristic = ARTSingleShare.currentCharacteristic;
    _writeCharacteristic = ARTSingleShare.writeCharacteristic;
    if (!_baby || !_currentPeripheral || !_notifyCharacteristic || !_writeCharacteristic) {
        return;
    }
    
    J_WeakSelf(self)
    // 监听蓝牙数据
    [_baby notify:_currentPeripheral characteristic:_notifyCharacteristic block:^(CBPeripheral *peripheral, CBCharacteristic *characteristics, NSError *error) {
        J_StrongSelf(self)
        [self.dataAnalysis parsingAnalysisData:characteristics.value];
//        self.isConnected = YES;
        NSLog(@"characteristics.value = %@",characteristics.value);
    }];
    
    // 数据写入成功
    [_baby setBlockOnDidWriteValueForCharacteristic:^(CBCharacteristic *characteristic, NSError *error) {
        NSLog(@"====数据写入成功name：%@",characteristic.value);
    }];
        
    // 断开连接
    [self.baby setBlockOnDisconnect:^(CBCentralManager *central, CBPeripheral *peripheral, NSError *error) {
        J_StrongSelf(self)

    }];
}

/// 治疗方案指令下发
- (void)startTreatmentDeliveryInstructions{
//    F0 5A 14 03 0B 00 06 58 02 00 00 00 00 00 00 00 01 00 00 00
    Byte byte[] = {0xF0,0x5A,0x14,0x03,0,0,0x06,0x58,0x02,0,0,0,0,0,0,0,0x01,0,0,0};
    if ([self.contentStr isEqualToString:@"压力性尿失禁"]){
        byte[4] = 0x0B;
    }else if([self.contentStr isEqualToString:@"混合性尿失禁"]){
        byte[4] = 0x0C;
    }else if([self.contentStr isEqualToString:@"急迫性尿失禁"]){
        byte[4] = 0x0D;
    }else if ([self.contentStr isEqualToString:@"人流术后疼痛"]){
        byte[4] = 0x0E;
    }else if([self.contentStr isEqualToString:@"慢性盆腔疼痛"]){
        byte[4] = 0x0F;
    }else if([self.contentStr isEqualToString:@"阴道松弛"]){
        byte[4] = 0x10;
    }else if([self.contentStr isEqualToString:@"性功能障碍"]){
        byte[4] = 0x11;
    }else if([self.contentStr isEqualToString:@"阴道口闭合"]){
        byte[4] = 0x12;
    }else if([self.contentStr isEqualToString:@"子宫内膜薄"]){
        byte[4] = 0x13;
    }else if([self.contentStr isEqualToString:@"脏器脱垂"]){
        byte[4] = 0x14;
    }
    
    if ([self.treatmentContent isEqualToString:@"常规训练模式（A方案）"]){
        byte[5] = 0x00;
        _trainingType = ARTPelvicfloormuscleTrainingType_common;
    }else if([self.treatmentContent isEqualToString:@"自由训练模式（B方案）"]){
        byte[5] = 0x01;
        _trainingType = ARTPelvicfloormuscleTrainingType_free;
    }
    NSData *data = [NSData dataWithBytes:byte length:20];
    [self.currentPeripheral writeValue:data forCharacteristic:self.writeCharacteristic type:CBCharacteristicWriteWithResponse];
    
    /*
     
     0x0B：P12:压力性尿失禁
     0x0C：P13:混合型尿失禁
     0x0D：P14:急迫性尿失禁
     0x0E：P15:人流术后镇痛
     0x0F：P16:慢性盆腔疼痛
     0x10：P17:阴道松弛
     0x11：P18:性功能障碍
     0x12：P19：阴道口闭合
     0x13：P20:子宫内膜薄
     0x14：P21:脏器脱垂
     */
    
    /*
     
     0x00 :常规疗程
     0x01:自定义
     0x02：疗程A
     0x03：疗程B
     0x04：疗程C
     0x05：疗程D
     0x06：疗程E
     */

}

- (void)floatingButtonClick:(UIButton *)btn{
    [self startTreatmentDeliveryInstructions];
    [self pushPage];
}

- (void)pushPage{
    ARTPelvicFloorTrainingDetailController *trainingDetailVC = [ARTPelvicFloorTrainingDetailController new];
    trainingDetailVC.titleStr = self.contentStr;
    trainingDetailVC.trainingType = _trainingType;
    [self.navigationController pushViewController:trainingDetailVC animated:YES];
}

/// 病症指令下发
/// @param index <#index description#>
- (void)symptomsInstructionsIssuedWith:(NSInteger)index{
    if (index >9) return;
    Byte treatmentOptionsByte[] = {0x0B,0x0C,0x0D,0x0E,0x0F,0x10,0x11,0x12,0x13,0x14};
    Byte byte[] = {0xF0,0x5A,0x14,0x03,treatmentOptionsByte[index],0,0x06,0,0,0,0,0,0,0,0,0,0,0,0,0};
    NSData *data = [NSData dataWithBytes:byte length:20];
    [self.currentPeripheral writeValue:data forCharacteristic:self.writeCharacteristic type:CBCharacteristicWriteWithResponse];

    /*
     
     0x0B：P12:压力性尿失禁
     0x0C：P13:混合型尿失禁
     0x0D：P14:急迫性尿失禁
     0x0E：P15:人流术后镇痛
     0x0F：P16:慢性盆腔疼痛
     0x10：P17:阴道松弛
     0x11：P18:性功能障碍
     0x12：P19：阴道口闭合
     0x13：P20:子宫内膜薄
     0x14：P21:脏器脱垂
     */
}

- (void)scrollToPageWithIndex:(NSInteger)index{
    for (ARTTreatmentCommonModel *commonModel in self.dataArrM) {
        commonModel.isSelected = NO;
    }
    ARTTreatmentCommonModel *commonModel = [self.dataArrM j_objectAtIndex:index];
    commonModel.isSelected = YES;
    self.contentStr = commonModel.titleStr;
    self.treatmentIndex = index;
    ARTTreatmentCommonItemModel *itemModel = [commonModel.list j_objectAtIndex:0];
    self.treatmentContent = itemModel.titleStr;
    [self.bottomCollectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:index] atScrollPosition:UICollectionViewScrollPositionTop animated:YES];
    [self.topCollectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:YES];
    [self.topCollectionView reloadData];
    [self symptomsInstructionsIssuedWith:index];
    NSLog(@"盆底肌康复训练self.contentStr = %@",self.contentStr);
}

/// 点击item
/// @param commonCell <#commonCell description#>
/// @param index <#index description#>
/// @param content <#content description#>
- (void)didSelectedCommonCell:(ARTTreatmentCommonCell *)commonCell didSelectedIndex:(NSInteger)index content:(NSString *)content{
    ARTTreatmentCommonModel *commonModel = [self.dataArrM j_objectAtIndex:self.treatmentIndex];
    for (NSInteger i =0, len = commonModel.list.count; i <len; i++) {
        ARTTreatmentCommonItemModel *itemModel = [commonModel.list j_objectAtIndex:i];
        if (index != commonModel.list.count -1){
            if (i == index){
                itemModel.isChoose = YES;
            }else{
                itemModel.isChoose = NO;
            }
        }
    }
    [self.bottomCollectionView reloadData];
    self.treatmentContent = content;
    if ([content isEqualToString:@"治疗记录"]){
        ARTPelvicFloorMusclesHistoryDetailController *historyDetailVC = [ARTPelvicFloorMusclesHistoryDetailController new];
        historyDetailVC.titleStr = self.contentStr;
        [self.navigationController pushViewController:historyDetailVC animated:YES];
    }
}


#pragma mark - collectionView Datasource & Delegate
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    if (collectionView == self.topCollectionView){
        return 1;
    }
    return self.dataArrM.count;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if (collectionView == self.topCollectionView){
        return self.dataArrM.count;
    }
    return 2;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (collectionView == self.topCollectionView){
        ARTTreatmentCommonScrollTitleCell *scrollTitleCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ARTTreatmentCommonScrollTitleCell" forIndexPath:indexPath];
        ARTTreatmentCommonModel *commonModel = [self.dataArrM j_objectAtIndex:indexPath.item];
        [scrollTitleCell dataRenderingWithItemModel:commonModel indexPath:indexPath];
        return scrollTitleCell;
    }else {
        ARTTreatmentCommonModel *commonModel = [self.dataArrM j_objectAtIndex:indexPath.section];
        if (indexPath.item == 0) {
            ARTTreatmentCommonScrollCell *scrollCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ARTTreatmentCommonScrollCell" forIndexPath:indexPath];
            scrollCell.scrollPictureArrM = commonModel.scrollPictureArrM;
            return scrollCell;
        }else{
            ARTTreatmentCommonCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ARTTreatmentCommonCell" forIndexPath:indexPath];
            [cell dataRenderingWithItemArrM:commonModel.list indexPath:indexPath];
            cell.delegate = self;
            return cell;
        }
    }
}


/** 返回footer高度 */
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section {
    return CGSizeZero;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout
  sizeForItemAtIndexPath: (NSIndexPath *)indexPath {
    ARTTreatmentCommonModel *commonModel = [self.dataArrM j_objectAtIndex:indexPath.item];
    if (collectionView == self.topCollectionView){
        return commonModel.itemSize;
    }else{
        if (indexPath.item == 0) {
            return CGSizeMake(kScreenWidth, 15*2 + 172);
        }
        return CGSizeMake(kScreenWidth, commonModel.list.count * 70);
    }
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return 0.00001;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    if (collectionView == self.topCollectionView){
        return 8;
    }
    return 0.00001;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (collectionView == self.topCollectionView){
        [self scrollToPageWithIndex:indexPath.item];
    }
}


- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    int index = scrollView.contentOffset.x / scrollView.width;
    if (index <= self.dataArrM.count) {
        [self scrollToPageWithIndex:index];
    }
}

#pragma mark UI
- (void)configUI{
    self.title = @"盆底肌肉康复治疗";
    self.view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.topCollectionView];
    self.topCollectionView.frame = CGRectMake(15, TOP_HEIGHT, self.view.width - 15*2, 60);
    [self.view addSubview:self.bottomCollectionView];
    self.bottomCollectionView.frame = CGRectMake(0, self.topCollectionView.bottom + 8, self.view.width, XCScreenH -BOTTOM_SAFE_HEIGHT -TOP_HEIGHT - 60);
    [self.view addSubview:self.floatingBtn];
    self.floatingBtn.frame = CGRectMake(52, self.view.height - J_SafeAreaBottomHeight - 44 - 10, XCScreenW - 52*2, 44);
}

#pragma mark ---get---
- (UICollectionView *)topCollectionView {
    if (!_topCollectionView) {
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
        flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        _topCollectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:flowLayout];
        _topCollectionView.delegate = self;
        _topCollectionView.dataSource = self;
        _topCollectionView.showsVerticalScrollIndicator = NO;
        _topCollectionView.showsHorizontalScrollIndicator = NO;
        _topCollectionView.backgroundColor = [UIColor whiteColor];
        [_topCollectionView registerClass:[ARTTreatmentCommonScrollTitleCell class] forCellWithReuseIdentifier:@"ARTTreatmentCommonScrollTitleCell"];
        if (@available(iOS 11.0, *)) {
            _topCollectionView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
    }
    return _topCollectionView;
}

- (UICollectionView *)bottomCollectionView{
    if (!_bottomCollectionView) {
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
        flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        _bottomCollectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:flowLayout];
        _bottomCollectionView.delegate = self;
        _bottomCollectionView.dataSource = self;
        _bottomCollectionView.showsVerticalScrollIndicator = NO;
        _bottomCollectionView.showsHorizontalScrollIndicator = NO;
        _bottomCollectionView.backgroundColor = [UIColor colorFromARGB:@"#FBFBFB"];
        _bottomCollectionView.pagingEnabled = YES;
        [_bottomCollectionView registerClass:[ARTTreatmentCommonCell class] forCellWithReuseIdentifier:@"ARTTreatmentCommonCell"];
        [_bottomCollectionView registerClass:[ARTTreatmentCommonScrollCell class] forCellWithReuseIdentifier:@"ARTTreatmentCommonScrollCell"];
        if (@available(iOS 11.0, *)) {
            _bottomCollectionView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
    }
    return _bottomCollectionView;
}


- (UIButton *)floatingBtn {
    if (!_floatingBtn) {
        _floatingBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_floatingBtn addTarget:self action:@selector(floatingButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        _floatingBtn.backgroundColor = [UIColor colorFromARGB:@"#0095B6"];
        _floatingBtn.layer.cornerRadius = 5;
        [_floatingBtn setTitleColor:[UIColor colorFromARGB:@"#FFFFFF"] forState:UIControlStateNormal];
        _floatingBtn.titleLabel.font = [UIFont regularFontWithFontSize:16];
        [_floatingBtn setTitle:@"开始治疗" forState:UIControlStateNormal];
    }
    return _floatingBtn;
}


- (ARTPelvicFloorMusclesDataAnalysis *)dataAnalysis{
    if (!_dataAnalysis) {
        _dataAnalysis = [ARTPelvicFloorMusclesDataAnalysis new];
    }
    return _dataAnalysis;
}

@end
